from dailyspents.model import orm
from dailyspents._exceptions import DatabaseException
from sqlalchemy.ext.selectresults import SelectResults

class GenericController(object):
    
    def __init__(self, user, class_):
        ''' 
        GenericController class contains some common methods to
        all controller class.
        Pobably, your controller class will get benefits from the methods
        defined here.
        '''
        self.user = user
        self.query = orm.session.query(class_)
        
    
    def getTotal(self):
        res = SelectResults(self.query)
        count = res.filter(orm.User.c.id == self.user.id).count()
        return count
    
    def getById(self, id_):
        try:
            return self.query.get_by(id = id_, user=self.user)
        except Exception, e:
            raise e
    
    def save(self, object_):
        try:
            orm.session.save_or_update(object_)
            orm.session.refresh(self.user)
            orm.session.flush()
            orm.session.refresh(object_)
        except Exception, e:
            orm.session.expunge(object_)
            raise e
            raise DatabaseException('Can\'t save the item.')
        
    def deleteById(self, id_):
        try:
            object_ = self.getById(id_)
            orm.session.delete(object_)
            orm.session.refresh(self.user)
            orm.session.flush()
        except Exception, e:
            orm.session.clear()
            print e
            raise DatabaseException('Can\'t delete the item.')
